package com.tlb.web;


import java.util.UUID;
import javax.servlet.http.*;
import com.tlb.ejb.*;
import com.tlb.dto.*;

public class AuthManager {

    public static String AUTH_COOKIE_NAME = "SESSION_UUID";
    private HttpServletRequest request = null;
    private HttpServletResponse response = null;
    
    
    public AuthManager() {
        
    }
    
    public AuthManager(HttpServletRequest request, HttpServletResponse response) throws Exception {
        this.request = request;
        this.response = response;
        
        
    }
    
    
    public Poster softAuthenticatePoster() throws Exception {
    	String uuid = null;
        Poster p = null;
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            for(Cookie c : cookies) {
                if(AUTH_COOKIE_NAME.equals(c.getName())) {
                    uuid = c.getValue();
                    break;
                }
            }
        }
        if(uuid != null) {
        	p = new PosterDAO().getPosterByUUID(uuid);
        }
        
    	if(request != null)
    		request.getSession().setAttribute("welcomeUser", p==null?"Guest":p.getUserName());

    	return p;        	
    
    }
    

    public Poster softAuthenticatePoster(int monikerId) throws Exception {
        Poster p = this.softAuthenticatePoster();
        boolean foundMonikerId = false;
        if(p == null) {
        	return p;
        }             
       
    	for(Moniker m : p.getMonikers()) {
    		if(m.getMonikerId() == monikerId) {
    			foundMonikerId = true;
    			break;
    		}
    	}        	
       
    	return foundMonikerId ? p : null;
    }    
    
    
    public Poster hardAuthenticatePoster() throws Exception {
        Poster p = this.softAuthenticatePoster();
        
        if(p != null) {
        	return p;
        }

        request.getRequestDispatcher("/login.jsp").forward(request, response);
        return null;    
    }

    
    
    public Poster hardAuthenticatePoster(int monikerId) throws Exception {
        Poster p = this.softAuthenticatePoster(monikerId);

        if(p != null)
        	return p;
        
        request.getRequestDispatcher("/login.jsp").forward(request, response);
        return null;    
    }
    
    
    
    
    
    public String logUserIn(int posterId) {
        String uuid = UUID.randomUUID().toString();
        new AuthDAO().recordUserLogin(posterId, uuid);
        
        return uuid;
    }
    
    
    
    
    
    
}
